package com.sgq.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sgq.config.redis.RedisService;
import com.sgq.entity.Permission;
import com.sgq.entity.User;
import com.sgq.utils.JwtUtils;
import com.sgq.utils.MenuTree;
import com.sgq.utils.Result;
import com.sgq.utils.UserInfo;
import com.sgq.vo.RouterVo;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: 83778
 * @date: 2024-09-19 10:42
 * @desc:
 */
@RestController
@RequestMapping("/api/sysUser")
public class SysUserController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisService redisService;

    //前端登录成功以后会默认调用
    @GetMapping("/getInfo")
    public Result getInfo() {
        //从Spring Security上下文获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //判断authentication对象是否为空
        if (authentication == null) {
            return Result.error().message("用户信息查询失败");
        }
        //获取用户信息
        User user = (User)authentication.getPrincipal();
        //用户权限集合
        List<Permission> permissionList = user.getPermissions();
        //获取角色权限编码字段
        Object[] roles =
                permissionList.stream()
                        .filter(Objects::nonNull)
                        .map(Permission::getCode)
                        .filter(Objects::nonNull)
                        .toArray();
        //创建用户信息对象
        //roles 用来判定 按钮存不存在
        UserInfo userInfo = new UserInfo(user.getId(), user.getNickName(), user.getAvatar(), null, roles);
        //返回数据
        return Result.ok(userInfo).message("用户信息查询成功");

    }

    /**
     * 获取路由信息
     * @return
     */
    @GetMapping("/getMenuList")
    public Result getMenuList() {
        //从Spring Security上下文获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取用户信息
        User user = (User) authentication.getPrincipal();
        //获取当前用户相应的权限
        List<Permission> permissionList = user.getPermissions() ;
        //获取当前用户目录和菜单
        List<Permission> collect = permissionList
                .stream()
                .filter(item -> item != null && item.getType() !=2)
                .collect(Collectors.toList());
        //找到当前用户所有的菜单和目录生成对应的父子关系
        List<RouterVo> routerVoList = MenuTree.makeRouterTree(collect,0L);
        //返回数据
        return Result.ok(routerVoList).message("菜单数据获取成功");
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response){

        String token = this.getToken(request);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null){
            //清除认证信息
            new SecurityContextLogoutHandler().logout(request,response,authentication);
            //清除token信息
            redisService.del(redisService.getPrefix()+token);

            return Result.ok().message("退出成功");
        }

        return Result.error().message("退出失败");
    }

    /**
     * 获取前端传值token
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request){
        //Authorization
        String token = request.getHeader(jwtUtils.getTokenHeader());

        if (ObjectUtils.isEmpty(token)){
            token = request.getParameter(jwtUtils.getTokenHeader());
        }

        return token;
    }
}
